package com.runfast.waimai.web.controller;

import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.dao.model.RunfastCuserExample;
import com.runfast.common.entity.validate.group.Create;
import com.runfast.common.security.captcha.NECaptchaVerifier;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.utils.UploadUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 我的界面接口
 */
@RestController("userWmMyController")
@RequestMapping(value = "/api/user/wm/my")
public class MyController {

    @Autowired
    private RunfastCuserService cuserService;

    @Autowired
    private RunfastSmsSendrecordService smsSendrecordService;

    @Autowired
    private RunfastComplainService complainService;

    @Autowired
    private RunfastCustomService customService;

    @Autowired
    private RunfastScorerecordService scorerecordService;

    @Autowired
    private RunfastBusinessallianceService businessallianceService;

    @Autowired
    private RunfastAgentApplicationService agentApplicationService;

    @Autowired
    private RunfastDriverApplicationService driverApplicationService;


    @Autowired
    private SmsService smsService;

    @Autowired
    private RunfastBusinessCommentService businessCommentService;

    @Autowired
    private RunfastActivityService activityService;

    @Value("${android.update.server.version}")
    private Integer serverVersion;
    @Value("${android.update.server.url}")
    private String serverUrl;
    @Value("${android.update.server.description}")
    private String serverDescription;

    /**
     * 修改用户信息
     *
     * @param cuser
     * @param token
     * @return
     */
    @PostMapping("/update")
    public Result update(@ModelAttribute RunfastCuser cuser, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        cuser.setId(userId);
        cuserService.updateByPrimaryKeySelective(cuser);
        return Result.ok("");
    }

    /**
     * 根据原密码修改密码
     *
     * @param oldPwd 原密码
     * @param newPwd 新密码
     * @param token
     * @return
     */
    @PostMapping("/updatePwdByOld")
    public Result updatePwdByOld(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        RunfastCuser cuser = new RunfastCuser();
        cuser.setPassword(newPwd);

        RunfastCuserExample cuserExample = new RunfastCuserExample();
        cuserExample.or().andIdEqualTo(userId).andPasswordEqualTo(oldPwd);

        int i = cuserService.updateByExampleSelective(cuser, cuserExample);
        if (i == 0) return Result.fail(ResultCode.FAIL, "原密码错误");

        return Result.ok("");
    }

    /**
     * 根据短信验证码修改密码
     *
     * @param smsCode 短信验证码
     * @param newPwd  新密码
     * @param mobile
     * @return
     */
    @PostMapping("/updatePwdBySmsCode")
    public Result updatePwdBySmsCode(@RequestParam String mobile, @RequestParam String smsCode, @RequestParam String newPwd) {


        RunfastSmsSendrecordExample smsSendrecordExample = new RunfastSmsSendrecordExample();
        smsSendrecordExample.or().andPhoneEqualTo(mobile).andSmstypeEqualTo(2).andXcodeEqualTo(smsCode);
        smsSendrecordExample.setOrderByClause("id desc");

        List<RunfastSmsSendrecord> smsSendrecordList = smsSendrecordService.selectByExample(smsSendrecordExample);
        if (smsSendrecordList.isEmpty()) return Result.fail(ResultCode.FAIL, "验证码错误");

        RunfastCuserExample cuserExample = new RunfastCuserExample();
        cuserExample.or().andMobileEqualTo(mobile);

        RunfastCuser cuserUpdate = new RunfastCuser();
        cuserUpdate.setPassword(newPwd);
        cuserService.updateByExampleSelective(cuserUpdate, cuserExample);


        return Result.ok("");
    }

    /**
     * 获取当前用户信息
     *
     * @param token
     * @return
     */
    @PostMapping("/info")
    public Result<RunfastCuser> list(@RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        return Result.ok("", cuser);
    }


    /**
     * 商户加盟
     *
     * @param businessalliance
     * @return
     */
    @PostMapping("/businessJoin")
    public Result businessJoin(@Validated(Create.class) @ModelAttribute RunfastBusinessalliance businessalliance, BindingResult bindingResult) {

        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null)
            return Result.fail(ResultCode.PARAMETER_ERROR, fieldError.getField() + " " + fieldError.getDefaultMessage());

        businessalliance.setCreateTime(new Date());
        businessallianceService.insertSelective(businessalliance);
        return Result.ok("");
    }

    /**
     * 城市代理申请
     *
     * @param agentApplication
     * @return
     */
    @PostMapping("/cityAgentJoin")
    public Result cityAgentJoin(@Validated(Create.class) @ModelAttribute RunfastAgentApplication agentApplication,BindingResult bindingResult) {



        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null)
            return Result.fail(ResultCode.PARAMETER_ERROR, fieldError.getField() + " " + fieldError.getDefaultMessage());


        agentApplication.setCreateTime(new Date());
        agentApplication.setStatus(0);
        agentApplicationService.insertSelective(agentApplication);
        return Result.ok("");
    }


    /**
     * 骑手应聘
     *
     * @param driverApplication
     * @return
     */
    @PostMapping("/driverJoin")
    public Result driverJoin(@Validated(Create.class) @ModelAttribute RunfastDriverApplication driverApplication, @RequestParam String smsCode, BindingResult bindingResult) {

        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null)
            return Result.fail(ResultCode.PARAMETER_ERROR, fieldError.getField() + " " + fieldError.getDefaultMessage());

        RunfastSmsSendrecordExample smsSendrecordExample = new RunfastSmsSendrecordExample();
        smsSendrecordExample.or().andSmstypeEqualTo(RunfastSmsSendrecord.SmsType.sms_join.getCode()).andPhoneEqualTo(driverApplication.getMobile()).andXcodeEqualTo(smsCode);
        smsSendrecordExample.setOrderByClause("id desc");
        List<RunfastSmsSendrecord> smsSendrecordList = smsSendrecordService.selectByExample(smsSendrecordExample);
        if (smsSendrecordList.isEmpty()) return Result.fail(ResultCode.FAIL, "验证码错误");

        driverApplication.setCreateTime(new Date());
        driverApplicationService.insertSelective(driverApplication);
        return Result.ok("");
    }


    /**
     * 用户投诉
     *
     * @param complain
     * @param token
     * @return
     */
    @PostMapping("/complain")
    public Result complain(@Validated(Create.class) @ModelAttribute RunfastComplain complain, BindingResult bindingResult, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null)
            return Result.fail(ResultCode.PARAMETER_ERROR, fieldError.getField() + " " + fieldError.getDefaultMessage());
        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        complain.setUserId(userId);
        complain.setUserName(cuser.getName());
        complain.setType(1);
        complain.setCreateTime(new Date());
        complainService.insertSelective(complain);

        return Result.ok("");
    }

    /**
     * 获取代理商客服
     *
     * @param agentId
     * @return
     */
    @PostMapping("/custom")
    public Result<RunfastCustom> custom(@RequestParam int agentId) {

        RunfastCustom custom = null;
        RunfastCustomExample customExample = new RunfastCustomExample();
        customExample.or().andAgenIdEqualTo(agentId).andTypeEqualTo(0);
        List<RunfastCustom> customList = customService.selectByExample(customExample);
        if (customList.isEmpty()) {
            custom = new RunfastCustom();
            custom.setMobile("400-0775248");

            return Result.ok("", custom);
        } else {
            return Result.ok("", customList.get(0));
        }


    }

    /**
     * 获取用户积分明细
     *
     * @param token
     * @return
     */
    @PostMapping("/scoreRecord")
    public Result<List<RunfastScorerecord>> scoreRecord(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        RunfastScorerecordExample scorerecordExample = new RunfastScorerecordExample();
        scorerecordExample.or().andCidEqualTo(userId);
        List<RunfastScorerecord> scorerecordList = scorerecordService.selectByExampleWithPageable(scorerecordExample, pageable);

        return Result.ok("", scorerecordList);
    }

    /**
     * 发送短信
     *
     * @param validate
     * @param mobile
     * @param smsType
     * @param request
     * @return
     */
    @PostMapping("/sendSms")
    public Result sendSms(@RequestParam(value = NECaptchaVerifier.REQ_VALIDATE, required = false) String validate, String mobile, @RequestParam RunfastSmsSendrecord.SmsType smsType, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        return smsService.sendSms(validate, mobile, smsType, remoteAddr);
    }


    /**
     * 检查app版本
     *
     * @param version
     * @return
     */
    @PostMapping("/checkVersion")
    public Result checkVersion(@RequestParam int version) {

        if (serverVersion == null || StringUtils.isBlank(serverUrl))
            return Result.fail(ResultCode.FAIL, "app版本更新配置信息为空");

        if (version < serverVersion) {
            Map<String, Object> update = new HashMap<>();
            update.put("serverVersion", serverVersion);
            update.put("serverDescription", serverDescription);
            update.put("serverUrl", serverUrl);

            return Result.ok("", update);
        } else return Result.ok("已经是最新版本");

    }


    /**
     * 获取用户评价
     *
     * @return
     */
    @PostMapping("/listComment")
    public Result listComment(@PageableDefault Pageable pageable) {

        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();
        Integer userId = cuser.getId();

        List<RunfastBusinessComment> businessCommentList = businessCommentService.find(null, userId, pageable);


        Map<String, Object> stat = businessCommentService.businessCommentStat(null, userId);
        Long count = 0L;

        if (stat != null) {
            count = (Long) stat.get("count");
            count = count==null?0L:count;

        }


        Map<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentCount", count);
        commentMap.put("commentList", businessCommentList);

        return Result.ok("", commentMap);
    }


    @PostMapping("/redActivityForPick")
    public Result<List<RunfastActivity>> redActivityForPick(@RequestParam Integer agentId, @PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return activityService.redActivityForPick(agentId, userId, false);
    }


    @PostMapping("/fileUpload")
    public Result fileUpload(@RequestParam MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        String extention = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        Random r = new Random();
        String newFileName = System.currentTimeMillis() + "_" + r.nextInt(10000) + extention;

        String filePath = "upload/" + newFileName;
        try {
            String key = UploadUtil.upload(file.getInputStream(), filePath);
            if (key != null) {
                return Result.ok("", key);
            } else {
                return Result.fail(ResultCode.FAIL, "上传文件失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(ResultCode.FAIL, "上传文件失败");
        }

    }

}
